#include "mythRTMPDecoder.hh"

int mythRTMPDecoder::MainLoop()
{
	srs_rtmp_t rtmp_in = NULL;
	srs_human_trace("[in]rtmp url: %s", _url.c_str());
	rtmp_in = srs_rtmp_create(_url.c_str());

	if (srs_rtmp_handshake(rtmp_in) != 0) {
		goto rtmp_destroy;
	}

	if (srs_rtmp_connect_app(rtmp_in) != 0) {
		goto rtmp_destroy;
	}

	if (srs_rtmp_play_stream(rtmp_in) != 0) {
		goto rtmp_destroy;
	}
	while (flag == 0){
		int size;
		char type;
		char* data;
		u_int32_t timestamp;

		if (srs_rtmp_read_packet(rtmp_in, &type, &timestamp, &data, &size) != 0) {
			goto rtmp_destroy;
		}
		if (type == SRS_RTMP_TYPE_VIDEO){
			FlvParser(data, size);
		}
	}
rtmp_destroy:
	if (rtmp_in)
		srs_rtmp_destroy(rtmp_in);
#ifdef WIN32
	// cleanup socket for windows.
	WSACleanup();
#endif
	return 0;
}

void mythRTMPDecoder::FlvParser(char* data,int len){
	//data[0] == 0x17;
	printf("write parse flv,%d\n", len);
	bool keyframe = (data[0] == 0x17);
	bool issps = (data[1] == 0x0);
	if (issps){
		int spslen = data[11] * 16 + data[12];
		putRaw((unsigned char*) &data[13], spslen);
		int ppsindex = 14 + spslen;
		int ppslen = data[ppsindex] * 16 + data[ppsindex + 1];
		putRaw((unsigned char*) &data[ppsindex + 2], ppslen);
	}
	else{
		//frame
		unsigned int _len = 0;
		for (int i = 0; i < 4; i++){
			_len *= 256;
			_len += (unsigned char) data[5 + i];
		}
		putRaw((unsigned char*) &data[9], _len);
	}
}

mythRTMPDecoder::~mythRTMPDecoder()
{
}

mythRTMPDecoder::mythRTMPDecoder(const char* url)
	:mythVirtualDecoder()
{
	_url = url;
}
